import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xindong/widgets/animation/xindong_animation_water_ripple.dart';

// 水波纹
class XinDongWaterRippleProvider with ChangeNotifier {
  final int timeCount = 5; // 显示水波纹持续时长 n x 100毫秒
  Timer? _countTimer;
  int _count = 0;

  // 构造函数
  XinDongWaterRippleProvider();

  // 外部调用
  static ChangeNotifierProvider createProvider({required int volume, double minWidth = 50.0}) {
    return ChangeNotifierProvider<XinDongWaterRippleProvider>(
      create: (_) {
        XinDongWaterRippleProvider provider = XinDongWaterRippleProvider();
        return provider;
      },
      child: XinDongWaterRippleContainer(volume: volume, minRadius: minWidth / 2),
    );
  }

  // 显示 设置一个阈值 建议 大于5的时候再开始画圈
  void show(int volume) {
    if (volume < 5) {
      return;
    }
    // print("大于5的时候再开始画圈");
    _count = timeCount;
    _countdown();
  }

  // 计数器
  void _countdown() {
    if (_countTimer != null && _countTimer?.isActive == true) {
      return;
    }
    _countTimer?.cancel();
    _countTimer = null;
    // 100毫秒一次
    _countTimer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      _count--;
      if (_count <= 0) {
        _count = 0;
        _countTimer?.cancel();
        notifyListeners();
      }
    });
  }

  @override
  void dispose() {
    _countTimer?.cancel();
    _countTimer = null;
    super.dispose();
  }
}

class XinDongWaterRippleContainer extends StatelessWidget {
  final int? volume;
  final double minRadius;

  const XinDongWaterRippleContainer({Key? key, this.volume, required this.minRadius}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Provider.of<XinDongWaterRippleProvider>(context, listen: false).show(volume ?? 0);

    return Consumer<XinDongWaterRippleProvider>(
      builder: (context, provider, child) {
        return provider._count <= 0
            ? const SizedBox()
            : XinDongAnimationWaterRipple(
                color: Colors.white,
                count: 2,
                minRadius: minRadius,
                maxRadius: minRadius + 12.5,
              );
      },
    );
  }
}
